local desc_1v1 = [[
  # uno模式简介

  从一人开始打牌，下家须依次打出与上家花色或点数相同的牌
  ___
  该模式下
  从一人开始打牌，下家须依次打出与上家花色或点数相同的牌，率先打完全部牌的玩家胜利！
  该模式下部分卡牌打出时获得额外效果：
  -----------------
  1.无懈可击，可任意打出，打出后你决定下家所需打出的花色。
  2.无中生有，打出后下家摸2张牌
  3.过河拆桥/顺手牵羊，打出后下家摸1张牌
  4.乐不思蜀/兵粮寸断，打出后下家跳过一回合
 

]]
local GameEvent=require "packages/jbs2/tableflow/unoflow"

-- FIXME: Disable same convert by param or extra data
local function rm(generals, g)
  local gt = Fk.generals[g].trueName
  for i, v in ipairs(generals) do
    if Fk.generals[v].trueName == gt then
      table.remove(generals, i)
      return
    end
  end
end


--
--技能获得
local function execGameEvent(type, ...)
  local event = GameEvent:new(type, ...)
  local _, ret = event:exec()
  return ret
end




local s1v1_getLogic = function()
  local m_1v1_logic = GameLogic:subclass("jbsuno_logic")
  function m_1v1_logic:prepareForStart()
    local room = self.room
    local players = room.players

    self:addTriggerSkill(GameRule)
    for _, trig in ipairs(Fk.global_trigger) do
      if trig.name ~= "mobile_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  
  function m_1v1_logic:run()
    -- default logic
    local room = self.room
    table.shuffle(self.room.players)
    self:assignRoles()
    self.room.game_started = true
    room:doBroadcastNotify("StartGame", "")
    room:adjustSeats()
    --[[ 因为未完工，在release版暂时不启用。
    for _, p in ipairs(room.players) do
      p.ai = SmartAI:new(p)
    end
    --]]
    self:chooseGenerals()
    self:prepareDrawPile()
    self:buildPlayerCircle()
    self:broadcastGeneral()
    self:attachSkillToPlayers()
    self:prepareForStart()
    self:action()
  end
  function m_1v1_logic:action()
    self:trigger(fk.GamePrepared)
    local room = self.room
    execGameEvent(GameEvent.UnoDrawInitial)
    while true do
      execGameEvent(GameEvent.UnoRound)
      if room.game_finished then break end
    end
  end

  function m_1v1_logic:prepareDrawPile()
    local room = self.room
    local allCardIds = Fk:getAllCardIds()
    --重新过滤卡组
    local filterCardIds = {}
    local while_cards = {"standard","standard_cards","maneuvering","jbsuno_cards"}
    local blacklist = { "amazing_grace"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(while_cards,card.package.name) or table.contains(blacklist, card.name) then
          table.removeOne(allCardIds, id)
          table.insert(room.void, id)
          room:setCardArea(id, Card.Void, nil)
        end
      if table.contains(while_cards,card.package.name) and not table.contains(blacklist, card.name)  then
        if not card.is_derived then
          table.insert(filterCardIds,id)
        end
      end
    end
    end
     
  
  

    local seed = math.random(2 << 32 - 1)
    table.shuffle(filterCardIds,seed)
    room.draw_pile = filterCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
    room:doBroadcastNotify("PrepareDrawPile", seed)
  end

  function m_1v1_logic:chooseGenerals()
    local room = self.room
    local generalNum = math.min(room:getSettings('generalNum'),5)
    local n = room:getSettings('enableDeputy') and 2 or 1
    local lord = room:getLord()
    local lord_generals = {}
    room:setTag("jbsunochange",1)
    if lord ~= nil then
      room.current = lord
    end
    local general_pile={}
    for _, g in ipairs(Fk.packages["unostart"].generals) do
      if g.name:startsWith("poke__") and not g.total_hidden then
        table.insertIfNeed(general_pile, g.name)
      end
    end
  
    local nonlord = room.players
    local generals = table.random(general_pile,#nonlord * generalNum)
    table.shuffle(generals)
    for i, p in ipairs(nonlord) do
      local arg=table.random(generals,generalNum)
      --local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
      p.request_data = json.encode{ arg, n }
      p.default_reply = table.random(arg, n)
    end
  
    room:notifyMoveFocus(nonlord, "AskForGeneral")
    room:doBroadcastRequest("AskForGeneral", nonlord)
  
    local selected = {}
    for _, p in ipairs(nonlord) do
      if p.general == "" and p.reply_ready then
        local general_ret = json.decode(p.client_reply)
        local general = general_ret[1]
        local deputy = general_ret[2]
        table.insertTableIfNeed(selected, general_ret)
        room:setPlayerGeneral(p, general, true, true)
        room:setDeputyGeneral(p, deputy)
      else
        room:setPlayerGeneral(p, p.default_reply[1], true, true)
        room:setDeputyGeneral(p, p.default_reply[2])
      end
      p.default_reply = ""
    end
  
    generals = table.filter(generals, function(g) return not table.contains(selected, g) end)
    room:returnToGeneralPile(generals)
  
    room:askForChooseKingdom(nonlord)
  end

  function m_1v1_logic:broadcastGeneral()--血量置为10血
    local room = self.room
    local players = room.players
  
    for _, p in ipairs(players) do
      assert(p.general ~= "")
      local general = Fk.generals[p.general]
      p.shield = general.shield 
      p.maxHp = general.maxHp
      p.hp =general.hp
      room:broadcastProperty(p, "role")     
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
      room:broadcastProperty(p, "deputyGeneral")
      room:broadcastProperty(p, "maxHp")
      room:broadcastProperty(p, "hp")
      room:broadcastProperty(p, "shield")
    end
  end
  return m_1v1_logic
end

local m_1v1_rule = fk.CreateTriggerSkill{
  name = "#jbsuno_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart,fk.GameOverJudge,fk.CardResponding},
  can_refresh = function(self, event, target, player, data)
    if event==fk.AfterCardsMove then
      if not player:isKongcheng() then return end
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand then
            return true
          end
        end
      end
    end
    else
      return target == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
    room:setBanner("@[:]jbsfire_rule","jbsuno-intro")
    elseif event == fk.GameOverJudge then
      local body = room:getPlayerById(data.who)
      local target=body
      for _, p in ipairs(room.players) do
        if p.rest>target.rest then
          target=p
        end
      end

      room:setTag("SkipGameRule", true)
      room:gameOver(target.role)
    elseif event == fk.AfterCardsMove then
      if player:isKongcheng() then 
        player._splayer:setDied(false)
        room:setPlayerRest(player, 99)
        room:killPlayer({ who = player.id })
      end
    else
      local unonext=function (player,room)
        if room:getTag("jbsunochange")>=0 then
          return player:getNextAlive(true, nil, true)
        else
          return player:getLastAlive(true, nil, true)
        end
        
      end
      local card=data.card
      if card.name=="nullification" then
        local suit={"heart", "spade", "club", "diamond"}
        local choice=room:askForChoice(player,suit,self.name,"#uno-choicewild")
        room:setBanner("@uno",{choice,""})

      elseif card.name=="indulgence" or card.name=="supply_shortage" then
        unonext(player,room):turnOver()
      elseif card.name=="ex_nihilo" then
        unonext(player,room):drawCards(2)
      elseif card.name=="dismantlement" or card.name=="snatch" then
        unonext(player,room):drawCards(1)
      elseif card.name=="unochange"  then
        local n=room:getTag("jbsunochange")
        room:setTag("jbsunochange",-n)
      end

    end
  end,
}








local m_1v1_mode = fk.CreateGameMode{
  name = "jbsuno_mode",
  minPlayer = 2,
  maxPlayer =8,
  rule = m_1v1_rule,
  logic = s1v1_getLogic,
  surrender_func = function(self, playedTime)
    return { { text = "time limitation: 2 min", passed = playedTime >= 120 } }
  end,
}
-- extension:addGameMode(m_1v1_mode)
Fk:loadTranslationTable{
  ["jbsuno_mode"] = "uno",
  [":jbsuno_mode"] = desc_1v1,
  ["@jbsfire_assignment"]="任务",
  ["jbsuno-intro"]="三国uno",
  [":jbsuno-intro"]=[[该模式下
  从一人开始打牌，下家须依次打出与上家花色或点数相同的牌，率先打完全部牌的玩家胜利！<br>该模式下部分卡牌打出时获得额外效果：
  <br>无懈可击，可任意打出，打出后你决定下家所需打出的花色。
  <br>无中生有，打出后下家摸2张牌
  <br>过河拆桥/顺手牵羊，打出后下家摸1张牌
  <br>乐不思蜀/兵粮寸断，打出后下家跳过一回合]],
  ["#jbsuno_rule"]="Uno",
  ["#uno-choicewild"]="选择一个花色，下家开始须打出此花色",

}

return m_1v1_mode
